
define(['utils', 'template', 'dialogTools','jquery/cookie'], function (utils, temp, dialogTools) {
    var global = window.$CONFIG || {};

    var RED_PACKET_CODE = 9;

    var bigScreenTopic = {
        // 初始化
        moduleTimer: null,
        moduleFlag: false,
        latestId: '',
        oldestId: '',
        allOldestId:'',

        // 配置
        isAllowAutoScroll:false,

        // 总队列数据队列
        historyCommentQueue:[],

        // 新拉取数据的数据队列
        newCommentQueue:[],

        // 远古时期的数据的队列
        ancientCommentQuene:[], 

        // 是否自动拉取定时器
        autoScrollTimer:null,

        // 最后一次显示的历史数据的标志
        lastHistoryIndex:0,

        // 新队列的数值
        lastNewCommentCount:0,

        // 定时拉取旧数据
        pullOldCommentTimer:null,

        // 总评论节点数
        totalCommentNodeNum:0,

        maxNodeNum: 30,

        // 红包停留时间
        redPacketMaskDelayTime: 5000,

        //置顶消息定时器
        sysMsgTimer:null,

        init: function (opt) {
            
            this.setConfig();

            this.getTopicList();

            // 初始化开启轮询模式切换
            this.initAutoModeSetting();

            this.initSysMsg();

        },

        initAutoModeSetting:function(){
            var me = this;
            var $invokeAutoModeBtn = $('.auto-mode-setting .btn-invoke');

            if($.cookie('is_allow_auto_scroll') != null){
                this.isAllowAutoScroll = $.cookie('is_allow_auto_scroll');
            }

            function _inlineClose(){
                $invokeAutoModeBtn.text('开启回放');
                $invokeAutoModeBtn.removeClass('open');
            }

            function _inlineOpen(){
                $invokeAutoModeBtn.text('关闭回放');
                $invokeAutoModeBtn.addClass('open');
            }
            if(me.isAllowAutoScroll == 1){
                _inlineOpen();
                me.invokeAutoModeScroll(1);
            }else{
               _inlineClose();
               me.invokeAutoModeScroll(0);
            }

            // $invokeAutoModeBtn.on('click',function(){
            //     if($(this).hasClass('open')){
            //         $.cookie('is_allow_auto_scroll',0);
            //         me.invokeAutoModeScroll(0);
            //         _inlineClose();
            //          window.location.href = '';
            //     }else{

            //         $.cookie('is_allow_auto_scroll',1);
            //         me.invokeAutoModeScroll(1);
            //         _inlineOpen();
            //         window.location.href = '';
                    
            //     }
            // });

            var oldUsed = $.cookie('is_allow_auto_scroll') || 0;

            setInterval(function(){

                if(window.PAGECONFIG.curPageName == 'topic'){
                    utils.loadUniversalConfig(W_WallId,function(data){
                        var used = 0;

                        if(!data  ||  (data.Used == 0)){
                            used = 0;
                        }else{
                            used = 1;
                        }

                        used = !data  ||  (data.Used == 0) ? 0 : 1;

                        if(oldUsed != used){
                            $.cookie('is_allow_auto_scroll',used);
                            window.location.href="";
                        }
                    });
                }
                
            },1000);

            // this.showRedPacket('fff');
        },

        getIsAllowAutoScroll:function(){
            var isAllow = false;
            return this.isAllowAutoScroll;
        },

        setConfig:function(){
            var style = '';

            var $styleNode = $('style').eq(0);

            // 字体颜色
            if(W_SKIN.BackgroundColor != '#000'){
                style += 'div.content-topic div.item div.txt span{color:' + W_SKIN.BackgroundColor + '}';
            }

            // 字体大小
            if(W_SKIN.FontSize){
                style += 'div.content-topic div.item div.txt span{font-size:' + W_SKIN.FontSize + '}';
            }

            // 评论框背景颜色
            if(W_SKIN.CommentBackgroundColor){
                style += 'div.content-topic div.item{background-color:' + W_SKIN.CommentBackgroundColor + '}';
            }

            // 评论框字体颜色
            if(W_SKIN.CommentBorderColor){
                style += 'div.content-topic div.item{border-color:' + W_SKIN.CommentBorderColor + '}';
            }

            $styleNode.append(style);

        },
        pushNewCommentToQueue:function(comment){
            var t = {   
                    Content:comment.Content,
                    ContentType:comment.ContentType,
                    CreateTime:comment.CreateTime,
                    Floor:comment.Floor,
                    Id:comment.Id,
                    NickName:comment.NickName,
                    Photo:comment.Photo,
                    ReplyToId:comment.ReplyToId,
                    UpdateTime:comment.UpdateTime,
                    UserId:comment.UserId
                };

                this.newCommentQueue.push(t);
        },
        pushHistoryCommentToQueue:function(comment){

            var t = {   
                    Content:comment.Content,
                    ContentType:comment.ContentType,
                    CreateTime:comment.CreateTime,
                    Floor:comment.Floor,
                    Id:comment.Id,
                    NickName:comment.NickName,
                    Photo:comment.Photo,
                    ReplyToId:comment.ReplyToId,
                    UpdateTime:comment.UpdateTime,
                    UserId:comment.UserId
                };

                this.historyCommentQueue.push(t);

        },
        pushAncientCommentToQueue:function(comment){
            var t = {   
                Content:comment.Content,
                ContentType:comment.ContentType,
                CreateTime:comment.CreateTime,
                Floor:comment.Floor,
                Id:comment.Id,
                NickName:comment.NickName,
                Photo:comment.Photo,
                ReplyToId:comment.ReplyToId,
                UpdateTime:comment.UpdateTime,
                UserId:comment.UserId
            };

            this.ancientCommentQuene.push(t);
        },
        pollingLatestData: function (topicId) {
            var that = this;
            that.moduleTimer = setInterval(function () {
                if (that.moduleFlag == true) return;
                that.moduleFlag = true;
                utils.ajax({
                    url: $CONFIG.REMOTE.WallURL+'/ajax/GetWallContentList',
                    data: {
                        WallId: global['wallid'],
                        TopicId: topicId,
                        MaxId: that.latestId
                    },
                    timeout: 5000,
                    success: function (json) {
                        if (json.successful) {
                            that.latestId = json.data.MaxId || that.latestId;

                            // 第一次进来
                            if(that.oldestId == '' && json.data.items && json.data.items.length > 0){
                                var lastIdx = json.data.items.length;
                                that.oldestId = json.data.items[lastIdx-1].Id;

                                // 后台的数据是倒序
                                json.data.items.reverse();

                            }

                            if(     json.data
                                &&  json.data.items
                                &&  json.data.items.length > 0){

                                for(var i = 0 ; i < json.data.items.length ; i ++){
                                    var item = json.data.items[i];

                                    // 如果有红包的话，就弹出红包遮罩
                                    if(item.ContentType == RED_PACKET_CODE){
                                        that.showRedPacket(item.NickName);

                                        if(that.isAllowAutoScroll == 1){
                                            that.pollCallback({items:[item]});
                                        }

                                    }else{
                                        that.pushNewCommentToQueue(item);
                                    }

                                    
                                    
                                }

                            }
                            
                            if(that.isAllowAutoScroll == 0){
                                that.pollCallback(json.data);
                            }
                            
                        }
                        that.moduleFlag = false;
                    },
                    error: function () {
                        that.moduleFlag = false;
                    }
                });
            }, 1000);
        },
        pollCallback: function (data) {
            if (data.items.length > 0) {
                var maxFloor = 0;
                if ($(".row-talking .item").first().length) {
                    maxFloor = parseInt($(".row-talking .item").first().data("floor")) + data.items.length;
                } else {
                    maxFloor = data.items.length;
                }
                for (var i = 0; i < data.items.length; i++) {
                    data.items[i].Content = this.processFacialExpression(data.items[i].Content);  //emoje解码
                    
                    //默认头像
                    data.items[i].Floor = maxFloor;
                    --maxFloor;
                    this.totalCommentNodeNum++;
                }
                this.setTopic(data);

                // 避免页面节点过，导致性能问题，超过一定数量后，删除最后一个节点

                if(this.totalCommentNodeNum > this.maxNodeNum){
                    var duration = this.totalCommentNodeNum - this.maxNodeNum;

                    for(var i = 0 ; i < duration ; i ++){
                        $('.row-talking .item:last-child').remove();
                    }

                    this.totalCommentNodeNum = this.maxNodeNum;
                    
                }
            }
        },
        getTopicList: function (topicid) {
            var that = this;

            var nestingMax = 10,
                nestingNum = 0;
            
            that.getOldestList(topicid, function () {

                that.allOldestId = that.oldestId;

                // 拉取老数据
                function _pullAllOldDataCallback(){

                    utils.ajax({
                        url: $CONFIG.REMOTE.WallURL+"/ajax/GetOldWallContentList",
                        data: {
                            WallId: global["wallid"],
                            TopicId: topicid,
                            MinId: that.allOldestId
                        },
                        success: function (json) {

                            // 如果数量为0，或者拉取10层后，停止拉动
                            if (json.successful 
                                && json.data.items.length > 0
                                && nestingNum <= nestingMax) {

                                nestingNum++;

                                var data = json.data;

                                // console.log(data);

                                that.allOldestId = data.MinId || that.allOldestId;
    
                                for (var i = 0; i < data.items.length; i++) {
                                    data.items[i].Content = that.processFacialExpression(data.items[i].Content);  //emoje解码

                                    // 插入远古时期评论队列
                                    that.pushAncientCommentToQueue(data.items[data.items.length - i - 1]);
                                }

                                setTimeout(function(){
                                    _pullAllOldDataCallback();
                                },3000);
                            }
                        }
                    });

                }

                if(that.isAllowAutoScroll == 1){
                    _pullAllOldDataCallback();
                }

                that.pollingLatestData(topicid);
            });

            $(".content-topic").scroll(function () {
                var $this = $(this);
                var _view = $this.height();
                var _content = $this.get(0).scrollHeight;
                var _scrollTop = $this.scrollTop();

                if (_content - _view - _scrollTop <= 50) {
                    if (that.scrollFlag) return;
                    that.scrollFlag = true;
                    $(".content-topic .scroll-tips").addClass('show');

                    that.getOldestList(topicid);
                }
            });
        },
        getOldestList: function (topicid, callback) {
            var that = this;

            utils.ajax({
                url: $CONFIG.REMOTE.WallURL+"/ajax/GetOldWallContentList",
                data: {
                    WallId: global["wallid"],
                    TopicId: topicid,
                    MinId: that.oldestId
                },
                success: function (json) {
                    if (json.successful) {
                        var data = json.data;

                        that.oldestId = data.MinId || that.oldestId;
                        if (data.Times && data.Times == 1) {
                            that.latestId = data.MaxId || that.latestId;
                        }
                        if (that.oldestId == '' && data.items.length == 0) {
                            $(".row-talking").fadeOut(function () {
                                $(".row-talking").show().html('<div class="tip" style="font-size: 2vw;color:white">一个评论也没有，快来互动吧</div>');
                            });
                            if (callback) callback();
                            return false;
                        } else if (data.items.length == 0) {
                            $(".content-topic .scroll-tips").removeClass('show');
                            return false;
                        }
                        var maxFloor = 0;
                        if ($(".row-talking .item").last().length > 0) {
                            maxFloor = parseInt($(".row-talking .item").last().data("floor"))-1;
                        } else {
                            maxFloor = data.Total;
                        }
                        for (var i = 0; i < data.items.length; i++) {
                            data.items[i].Content = that.processFacialExpression(data.items[i].Content);  //emoje解码
                            data.items[i].Floor = maxFloor;
                            --maxFloor;

                            // 插入新评论队列
                            // 红包数据除外
                            if(data.items[data.items.length - i - 1].ContentType != RED_PACKET_CODE){
                                that.pushHistoryCommentToQueue(data.items[data.items.length - i - 1]);
                            }
                            
                        }
                        // console.log(that.historyCommentQueue);
                        that.setTopic(data, 2);

                        if (callback) callback(data);

                       
                    }
                    that.scrollFlag = false;
                },
                error: function () {
                    $(".content-topic .scroll-tips").removeClass('show');
                    that.scrollFlag = false;
                }
            });
        },
        floor:0,
        setTopic: function (data,type) {
            var that = this;
            for (var i = 0; i < data.items.length; i++) {
                var obj = data.items[i];

                if (obj.ContentType && obj.ContentType == 1) {
                    obj.Content = decodeURIComponent(obj.Content);
                }

                //如果是红包
                if(obj.ContentType && obj.ContentType == RED_PACKET_CODE){
                    obj.Content = CONFIG.URL.App + "/swallv5/dist/img/red-packet.png";
                    obj.Photo = CONFIG.URL.App + "/swallv5/dist/img/admin_avatar.png";
                    obj.NickName = '系统红包';
                }
            }
            
            data.WallDetail = W_Data;
            data.isHiddenFloor = this.isAllowAutoScroll == 1 ?  true : false;

            var topicListHtml = temp.render("topicItem",data);
            if ($(".row-talking .tip").length) {
                $(".row-talking .tip").remove();
            }
            
            //type  1:htm  2:append
            if (type == 1) {
                $(".row-talking").html(topicListHtml);
                $(".row-talking .item").slideDown(function () {
                    $(this).removeAttr("style");
                });
            } else if(type == 2) {
                $(".row-talking").append(topicListHtml);
                $(".row-talking .item").slideDown(function () {
                    $(this).removeAttr("style");
                });
            } else {
                $(".row-talking").prepend(topicListHtml);
                $(".row-talking .item").slideDown(function () {
                    $(this).removeAttr("style");
                });
            }
            $(".content-topic .scroll-tips").removeClass('show');
        },
        emojies:['/::)','/::~','/::B','/::|','/:8-)','/::<','/::$','/::X','/::Z','/::\'(','/::-|','/::@','/::P','/::D','/::O','/::(','/::+','/:Cb','/::Q','/::T','/:,@P','/:,@-D','/::d','/:,@o','/::g','/:|-)','/::!','/::L','/::>','/::,@','/:,@f','/::-S','/:?','/:,@x','/:,@@','/::8','/:,@!','/:!!!','/:xx','/:bye','/:wipe','/:dig','/:handclap','/:&-(','/:B-)','/:<@','/:@>','/::-O','/:>-|','/:P-(','/::\'|','/:X-)','/::*','/:@x','/:8*','/:pd','/:<W>','/:beer','/:basketb','/:oo','/:coffee','/:eat','/:pig','/:rose','/:fade','/:showlove','/:heart','/:break','/:cake','/:li','/:bome','/:kn','/:footb','/:ladybug','/:shit','/:moon','/:sun','/:gift','/:hug','/:strong','/:weak','/:share','/:v','/:@)','/:jj','/:@@','/:bad','/:lvu','/:no','/:ok','/:love','/:<L>','/:jump','/:shake','/:<O>','/:circle','/:kotow','/:turn','/:skip','/[挥手]','/:#-0','/[街舞]','/:kiss','/:<&','/:&>'],
        processFacialExpression: function (str) {
            if (str) {
                //str = str.replaceAll('<', '&lt;');
                for (var i = 0; i < this.emojies.length; i++) {
                    if (str.indexOf('/:', 0) >= 0) {
                        str = str.replaceAll(this.emojies[i], '<img src="'+$CONFIG.StaticURL+'/img/weixin/emoji/' + i + '.png"/>');
                    } else {
                        break;
                    }
                }
                return str;
            } else {
                return str;
            }
        },
        invokeAutoModeScroll:function(isAllow){
            var me = this;

            var t = '';

            var duration = 3000;

            // 如果允许的话
            if(this.isAllowAutoScroll == 1){

               
                // $('.row-talking .all-floor').hide();
                // me.autoScrollTimer = clearInterval(me.autoScrollTimer);
                // 
                me.autoScrollTimer = setInterval(function(){

                    //优先拉取新队列信息
                    if(me.newCommentQueue.length > 0){

                        t = me.newCommentQueue.pop();

                        if(t.ContentType != RED_PACKET_CODE){
                            me.pollCallback({items:[t]});

                            //红包不进历史队列
                            me.pushHistoryCommentToQueue(t);
                        }
                        

                    }
                    // 其次拉远古时期列表
                    else if(me.ancientCommentQuene.length > 0){
                        t = me.ancientCommentQuene.shift();

                        if(t.ContentType != RED_PACKET_CODE){
                            me.pollCallback({items:[t]});

                            //红包不进历史队列
                            me.pushHistoryCommentToQueue(t);
                        }

                    }else{
                        var len = me.historyCommentQueue.length;

                        // 如果小于6条，不轮询
                        if(    me.newCommentQueue.length + me.historyCommentQueue.length <= 6
                            && me.lastHistoryIndex == 0){
                            return;
                        }
                        if(len > 0){

                            me.lastHistoryIndex = (me.lastHistoryIndex) % len;
                            var index = me.lastHistoryIndex;

                            me.pollCallback({items:[me.historyCommentQueue[index]]});
                            me.lastHistoryIndex = me.lastHistoryIndex + 1 ;

                        }
                    }

                },duration);

                

            }else if(!isAllow){

                me.autoScrollTimer = clearInterval(me.autoScrollTimer);

            }
        },

        showRedPacket:function(msg){
            var me = this;

            var redPacketMask = $('.red-packet-mask');
            redPacketMask.find('.words').text(msg);
            redPacketMask.fadeIn();

            setTimeout(function(){
                redPacketMask.fadeOut();
            },me.redPacketMaskDelayTime);
        },
        initSysMsg: function () {
            var _msgEle = $(".row-sysmsg");
            var _msgTitle = $(".row-sysmsg .msg-title");
            var _msgContent = $(".row-sysmsg .msg-content");
            setInterval(function () {
                if (window.PAGECONFIG.curPageName == 'topic') {
                    utils.ajax({
                        url: $CONFIG.REMOTE.WallURL + '/ajax/GetSugesstionMsgs',
                        data: {
                            WallId: global['wallid']
                        },
                        timeout: 5000,
                        success: function (json) {
                            if (json.successful && json.data != null) {
                                if (json.data.MsgType == 1) {
                                    _msgTitle.html("有新文件！");
                                    _msgContent.html("管理员上传了文件《" + json.data.Title + "》，请在手机端下载查看。");
                                } else if (json.data.MsgType == 2) {
                                    _msgTitle.html("有新消息！");
                                    _msgContent.html("管理员向你发送了一个链接，请在手机端点击查看。");
                                } else {
                                    _msgTitle.html(json.data.Title);
                                    _msgContent.html(json.data.Content);
                                }
                                _msgEle.fadeIn();
                            } else {
                                _msgEle.fadeOut();
                            }
                        },
                        error: function () {
                            
                        }
                    });
                }

            }, 5000);

            // this.showRedPacket('fff');
        }
    };
    return bigScreenTopic;
});